
import axios from 'axios'
import { Toast } from 'vant'
import router from '../router'
import storage from '@/utils/storage'
let timer: any = null
axios.defaults.baseURL = process.env.NODE_ENV == 'development' ? '//47.99.134.126:28019/api/v1' : '//47.99.134.126:28019/api/v1'
axios.defaults.withCredentials = true
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['token'] = storage.get('token') || ''
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.interceptors.request.use((config: any) => {
  config.timer = setTimeout(() => {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    timer = null;
  }, 1000);
  return Promise.resolve(config);
})
axios.interceptors.response.use((res: any) => {
  Toast.clear();
  clearTimeout(res.config.timer)
  res.config.timer = null
  if (typeof res.data !== 'object') {
    Toast.fail('服务端异常！')
    return Promise.reject(res)
  }
  if (res.data.resultCode != 200) {
    if (res.data.message) Toast.fail(res.data.message)
    if (res.data.resultCode == 416) {
      router.push({ path: '/login' })
    }
    return Promise.reject(res.data)
  }

  return res.data
})

export default axios
